package com.charonmc.commands;

import com.charonmc.CharonLogin;
import com.charonmc.utils.Md5Utils;
import com.charonmc.utils.TokenUtils;
import com.charonmc.utils.mysql.SqlManager;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.Objects;


public class Login implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (sender instanceof Player){
            Player player = (Player) sender;
            if (CharonLogin.loginPlayers.contains(player)){
                return true;
            }
            //占位符
            if (args.length == 1) {
                BukkitRunnable playerLogin = new BukkitRunnable() {
                    @Override
                    public void run() {
                        boolean isPlayerRegister;
                        try {
                            SqlManager SqlManager = new SqlManager("charonmc");
                            isPlayerRegister = !SqlManager.createQuery()
                                    .inTable("players")
                                    .selectColumns("player_id")
                                    .addCondition("player_name", player.getPlayer().getName())
                                    .build()
                                    .execute()
                                    .isNull();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        if (!isPlayerRegister){
                            sender.sendMessage("§7");
                            sender.sendMessage("§7你需先进行注册");
                            sender.sendMessage("§7/register §f§l密码 重复密码");
                        } else {
                            try {
                                SqlManager SqlManager = new SqlManager("charonmc");
                                Object password = SqlManager.createQuery()
                                        .inTable("players")
                                        .selectColumns("password")
                                        .addCondition("player_name", player.getPlayer().getName())
                                         .build()
                                        .execute()
                                        .first();
                                if (Objects.equals(Md5Utils.getMd5(args[0], player), password.toString())){
                                    //密码正确，登录成功
                                    sender.sendMessage("§a登录成功,GL&HF");
                                    CharonLogin.loginPlayers.add(player);
                                    CharonLogin.noLoginPlayers.remove(player);
                                    CharonLogin.loginErrorTime.remove(player);
                                    Object playerId = SqlManager.createQuery()
                                            .inTable("players")
                                            .selectColumns("player_id")
                                            .addCondition("player_name", player.getPlayer().getName())
                                            .build()
                                            .execute()
                                            .first();
                                    //在这里更新Token
                                    SqlManager.createUpdate()
                                            .inTable("players")
                                            .addColumnNames(new String[]{"token"})
                                            .addParams(new Object[]{TokenUtils.getToken(player)})
                                            .addCondition("player_id", playerId)
                                            .build()
                                            .execute();
                                    Object autologin = SqlManager.createQuery()
                                            .inTable("player_set")
                                            .selectColumns("auto_login")
                                            .addCondition("player_id", playerId)
                                            .build()
                                            .execute()
                                            .first();
                                    if ((int) autologin == 0){
                                        BaseComponent bs1 = new TextComponent("§7Charon 为您提供§a自动登录服务 §7(点击开启)");
                                        bs1.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§a开启自动登录")}));
                                        bs1.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/AutoLogin"));
                                        ((Player) sender).spigot().sendMessage(bs1);
                                    } else {
                                        BaseComponent bs2 = new TextComponent("§7您已开启§a自动登录服务 §7(点击关闭)");
                                        bs2.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{new TextComponent("§c关闭自动登录")}));
                                        bs2.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/AutoLogin"));
                                        ((Player) sender).spigot().sendMessage(bs2);
                                    }
                                } else {
                                    sender.sendMessage("§c§l密码错误");
                                    if (CharonLogin.loginErrorTime.get(player) <= 0){
                                        BukkitRunnable kickTask = new BukkitRunnable() {
                                            @Override
                                            public void run() {
                                                player.kickPlayer("§c密码错误次数过多！\n" +
                                                        "§7不必担心，这只是一种保护措施，它可以保护你的密码于暴力破解。\n" +
                                                        "§7如果您忘记密码，请求助管理员。");
                                            }
                                        };
                                        Bukkit.getScheduler().runTask(CharonLogin.instance, kickTask);
                                    }
                                    Integer time = CharonLogin.loginErrorTime.get(player);
                                    time -= 1;
                                    CharonLogin.loginErrorTime.put(player, time);
                                }
                                SqlManager.close();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                };
            playerLogin.runTaskAsynchronously(CharonLogin.instance);
            } else {
                sender.sendMessage("§c§l参数错误！");
                sender.sendMessage("§7请使用 §f/l (密码) §7进行登录。");
            }
        }else{
            sender.sendMessage("§c§l该命令只能由玩家执行！");
        }
        return true;
    }
}
